<template>
  <div class="app-container">
    <el-dialog :title="'订单导入（建议.xlsx格式）'" :destroy-on-close="true" :visible.sync="importOpen" width="75%" append-to-body :close-on-press-escape="false" :close-on-click-modal="false" :before-close="close" class="app-container-compactness">

      <!-- 上传组件     -->
      <el-collapse-transition>
        <upload-excel-component v-show="uploadRadio == 1" style="margin-bottom: 12px;" :on-success="handleSuccess" :before-upload="beforeUpload" />
      </el-collapse-transition>
      <div class="btn-box">

        <div class="btn-left">
          <el-button icon="el-icon-upload2" type="danger" :disabled="!multipleSelection.length" @click="uploadData">选中上传</el-button>
          <el-button icon="el-icon-delete" style="margin-left: 0" type="warning" :disabled="!multipleSelection.length" @click="deleteChecked">删除选中</el-button>
          <!--          <el-button icon="el-icon-milk-tea" style="margin-left: 0" type="warning" @click="clearAllSuccess">清空已成功</el-button>-->
        </div>

        <div class="btn-right">
          <el-button type="primary" style="margin-left: 0" icon="el-icon-plus" @click="insertEvent()">头部插入</el-button>
          <el-button type="danger" style="margin-left: 0" icon="el-icon-plus" @click="insertEvent(-1)">尾部插入</el-button>
        </div>
        <!--      <el-button @click="validAllEvent">整个表格校验</el-button>-->
        <!--      <el-button @click="fullValidEvent">校验</el-button>-->
      </div>

      <ux-grid
        ref="plxTable"
        v-loading="dialogLoading"
        :cell-style="{height:'24px'}"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        :element-loading-text="loadingText"
        size="mini"
        border
        :show-summary="true"
        :show-overflow="'title'"
        :show-header-overflow="'title'"
        keep-source
        stripe
        :rules="rules"
        height="500"
        :edit-config="{trigger: 'click', mode: 'cell'}"
        :checkbox-config="{checkMethod: selectable, highlight: true}"
        @selection-change="handleSelectionChange"
      >
        <ux-table-column type="checkbox" width="60" />
        <ux-table-column type="index" title="行号" width="80" />

        <ux-table-column width="100px" resizable prop="orderId" :edit-render="{autofocus: '.el-input__inner'}" field="orderId" title="订单编号">
          <template v-slot:edit="scope">
            <el-input v-model="scope.row.orderId" />
          </template>
          <template v-slot="{ row }">{{ row.orderId }}</template>
        </ux-table-column>

        <ux-table-column width="100px" resizable prop="orderDate" :edit-render="{autofocus: '.el-input__inner'}" field="orderDate" title="订单日期">
          <template v-slot:edit="scope">
            <el-input v-model="scope.row.orderDate" />
          </template>
          <template v-slot="{ row }">{{ row.orderDate }}</template>
        </ux-table-column>

        <ux-table-column width="100px" resizable prop="contactName" :edit-render="{autofocus: '.el-input__inner'}" field="contactName" title="收件人姓名">
          <template v-slot:edit="scope">
            <el-input v-model="scope.row.contactName" />
          </template>
          <template v-slot="{ row }">{{ row.contactName }}</template>
        </ux-table-column>

        <ux-table-column width="100px" resizable prop="contactCode" :edit-render="{autofocus: '.el-input__inner'}" field="contactCode" title="收件人证件号">
          <template v-slot:edit="scope">
            <el-input v-model="scope.row.contactCode" />
          </template>
          <template v-slot="{ row }">{{ row.contactCode }}</template>
        </ux-table-column>

        <ux-table-column width="100px" resizable prop="contactMobile" :edit-render="{autofocus: '.el-input__inner'}" field="contactMobile" title="联系电话">
          <template v-slot:edit="scope">
            <el-input v-model="scope.row.contactMobile" />
          </template>
          <template v-slot="{ row }">{{ row.contactMobile }}</template>
        </ux-table-column>

        <ux-table-column width="100px" resizable prop="buyerName" :edit-render="{autofocus: '.el-input__inner'}" field="buyerName" title="订购人">
          <template v-slot:edit="scope">
            <el-input v-model="scope.row.buyerName" />
          </template>
          <template v-slot="{ row }">{{ row.buyerName }}</template>
        </ux-table-column>

        <ux-table-column width="100px" resizable prop="ConsigneeCode" :edit-render="{autofocus: '.el-input__inner'}" field="ConsigneeCode" title="订购人证件号">
          <template v-slot:edit="scope">
            <el-input v-model="scope.row.ConsigneeCode" />
          </template>
          <template v-slot="{ row }">{{ row.ConsigneeCode }}</template>
        </ux-table-column>

        <ux-table-column width="100px" resizable prop="amount" :edit-render="{autofocus: '.el-input__inner'}" field="amount" title="商品金额">
          <template v-slot:edit="scope">
            <el-input v-model="scope.row.amount" />
          </template>
          <template v-slot="{ row }">{{ row.amount }}</template>
        </ux-table-column>

        <ux-table-column width="100px" resizable prop="payOrderNo" :edit-render="{autofocus: '.el-input__inner'}" field="payOrderNo" title="支付交易号">
          <template v-slot:edit="scope">
            <el-input v-model="scope.row.payOrderNo" />
          </template>
          <template v-slot="{ row }">{{ row.payOrderNo }}</template>
        </ux-table-column>

        <ux-table-column width="100px" resizable prop="contactAddr" :edit-render="{autofocus: '.el-input__inner'}" field="contactAddr" title="收货地址省市区">
          <template v-slot:edit="scope">
            <el-input v-model="scope.row.contactAddr" />
          </template>
          <template v-slot="{ row }">{{ row.contactAddr }}</template>
        </ux-table-column>

        <ux-table-column width="100px" resizable prop="detailAddr" :edit-render="{autofocus: '.el-input__inner'}" field="detailAddr" title="详细地址">
          <template v-slot:edit="scope">
            <el-input v-model="scope.row.detailAddr" />
          </template>
          <template v-slot="{ row }">{{ row.detailAddr }}</template>
        </ux-table-column>

        <ux-table-column align="center" width="100px" resizable field="HNACARD" prop="HNACARD" title="使用预付卡支付" :edit-render="{autofocus: '.el-input__inner'}">
          <template v-slot:edit="scope">
            <el-select v-model="scope.row.HNACARD" @change="$refs.plxTable.updateStatus(scope)">
              <el-option label="使用" value="1" />
              <el-option label="不使用" value="0" />
            </el-select>
          </template>
          <template v-slot="{ row }">{{ getHNACARDLabel(row) }}</template>
        </ux-table-column>

        <ux-table-column width="100px" resizable prop="distributionfee" :edit-render="{autofocus: '.el-input__inner'}" field="distributionfee" title="运费">
          <template v-slot:edit="scope">
            <el-input v-model="scope.row.distributionfee" />
          </template>
          <template v-slot="{ row }">{{ row.distributionfee }}</template>
        </ux-table-column>

        <ux-table-column width="100px" resizable prop="discount" :edit-render="{autofocus: '.el-input__inner'}" field="discount" title="优惠金额">
          <template v-slot:edit="scope">
            <el-input v-model="scope.row.discount" />
          </template>
          <template v-slot="{ row }">{{ row.discount }}</template>
        </ux-table-column>

        <ux-table-column width="100px" resizable prop="realPayment" :edit-render="{autofocus: '.el-input__inner'}" field="realPayment" title="实付金额">
          <template v-slot:edit="scope">
            <el-input v-model="scope.row.realPayment" />
          </template>
          <template v-slot="{ row }">{{ row.realPayment }}</template>
        </ux-table-column>

        <ux-table-column width="100px" resizable prop="source_platform_no" :edit-render="{autofocus: '.el-input__inner'}" field="source_platform_no" title="申报订单编号">
          <template v-slot:edit="scope">
            <el-input v-model="scope.row.source_platform_no" />
          </template>
          <template v-slot="{ row }">{{ row.source_platform_no }}</template>
        </ux-table-column>

        <!--        <ux-table-column width="100px" resizable prop="pay_type" :edit-render="{autofocus: '.el-input__inner'}" field="pay_type" title="支付方式">-->
        <!--          <template v-slot:edit="scope">-->
        <!--            <el-input v-model="scope.row.pay_type" />-->
        <!--          </template>-->
        <!--          <template v-slot="{ row }">{{ row.pay_type }}</template>-->
        <!--        </ux-table-column>-->

        <ux-table-column width="100px" resizable prop="pay_time" :edit-render="{autofocus: '.el-input__inner'}" field="pay_time" title="支付时间">
          <template v-slot:edit="scope">
            <el-input v-model="scope.row.pay_time" />
          </template>
          <template v-slot="{ row }">{{ row.pay_time }}</template>
        </ux-table-column>

        <!--        <ux-table-column width="100px" resizable prop="tradeType" :edit-render="{autofocus: '.el-input__inner'}" field="tradeType" title="贸易类型">-->
        <!--          <template v-slot:edit="scope">-->
        <!--            <el-input v-model="scope.row.tradeType" />-->
        <!--          </template>-->
        <!--          <template v-slot="{ row }">{{ row.tradeType }}</template>-->
        <!--        </ux-table-column>-->

        <ux-table-column width="100px" resizable prop="goods_spu" :edit-render="{autofocus: '.el-input__inner'}" field="goods_spu" title="订单商品编号">
          <template v-slot:edit="scope">
            <el-input v-model="scope.row.goods_spu" />
          </template>
          <template v-slot="{ row }">{{ row.goods_spu }}</template>
        </ux-table-column>

        <ux-table-column width="100px" resizable prop="sku_id" :edit-render="{autofocus: '.el-input__inner'}" field="sku_id" title="订单商品规格名称">
          <template v-slot:edit="scope">
            <el-input v-model="scope.row.sku_id" />
          </template>
          <template v-slot="{ row }">{{ row.sku_id }}</template>
        </ux-table-column>

        <ux-table-column width="100px" resizable prop="goods_num" :edit-render="{autofocus: '.el-input__inner'}" field="goods_num" title="订单商品数量">
          <template v-slot:edit="scope">
            <el-input v-model="scope.row.goods_num" />
          </template>
          <template v-slot="{ row }">{{ row.goods_num }}</template>
        </ux-table-column>

        <ux-table-column width="100px" resizable prop="goods_price" :edit-render="{autofocus: '.el-input__inner'}" field="goods_price" title="订单商品金额">
          <template v-slot:edit="scope">
            <el-input v-model="scope.row.goods_price" />
          </template>
          <template v-slot="{ row }">{{ row.goods_price }}</template>
        </ux-table-column>

        <!--        <ux-table-column prop="number" :edit-render="{autofocus: '.el-input__inner'}" field="number" title="数量*">-->
        <!--          <template v-slot:edit="scope">-->
        <!--            <el-input v-model="scope.row.number" @change="changeTableRowNumber(scope.row,$event)" />-->
        <!--          </template>-->
        <!--          <template v-slot="{ row }">{{ row.number }}</template>-->
        <!--        </ux-table-column>-->

        <ux-table-column
          align="center"
          width="80"
          fixed="right"
        >
          <template slot="header" slot-scope="scope">
            <span style="color: #67C23A;">操作</span>
          </template>
          <template v-slot="{ row }">
            <i class="el-icon-copy-document" style="font-weight: 1000;" @click="copyRow(row)" />
            <i class="el-icon-delete" style="margin-left: 5px; color: red;font-weight: 1000;" @click="delRow(row)" />
          </template>
        </ux-table-column>

        <!--      <ux-table-column-->
        <!--        title="操作"-->
        <!--        width="200"-->
        <!--        fixed="right"-->
        <!--      >-->
        <!--        <template v-slot="{ row }">-->
        <!--          &lt;!&ndash;判断行是否激活了, 编辑按钮执行的方式就是为了去激活&ndash;&gt;-->
        <!--          <template v-if="$refs.plxTable.isActiveByRow(row)">-->
        <!--            <el-button type="primary" @click="saveEvent(row)">保存</el-button>-->
        <!--            <el-button @click="cancelRowEvent(row)">取消</el-button>-->
        <!--          </template>-->
        <!--          <template v-else>-->
        <!--            <el-button @click="editRowEvent(row)">编辑</el-button>-->
        <!--          </template>-->
        <!--        </template>-->
        <!--      </ux-table-column>-->
      </ux-grid>

      <div style="margin:5px 0; display: flex;justify-content: flex-end">
        <div>
          <el-radio v-model="uploadRadio" label="1" @input="toggleUploadRadio">显示上传组件</el-radio>
          <el-radio v-model="uploadRadio" label="2" @input="toggleUploadRadio">隐藏</el-radio>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { getConversionList, getProject, traySurplus, getConfigLevel3 } from '@/api/storehouse'
import { providerList } from '@/api/basics'
import { importOrder2 } from '@/api/externalGoods'
import { att, createAdd, locationBatchCreate, locationSearchNum, seatList } from '@/api/stock'
export default {
  name: 'OrderImport',
  components: { UploadExcelComponent },
  props: {
    importOpen: {
      type: Boolean,
      default: false
    },
    dialogTitle: {
      type: String,
      default: ''
    },
    // warehousingSonId: {
    //   type: [String, Number, Boolean],
    //   default: ''
    // },
    form: {
      type: [String, Number, Boolean, Object],
      default: null
    }
  },
  data() {
    const projectClientRules = ({ cellValue, rule }) => {
      if (!Array.isArray(cellValue) || cellValue.length != 2) {
        return new Error('请选择项目和委托方')
      }
    }
    return {
      total_number: 0,
      uploadRadio: '2',
      loadingText: '',
      btnMiddleValue: false,
      dialogLoading: false,
      clientParams: {
        page: 1,
        limit: 9999,
        account_code: undefined,
        account_name: undefined
      },
      support_yfp: true,
      config_options: [],
      clientList: [],
      ConversionList: [],
      selectList: [],
      multipleSelection: [],
      err_xid_arr: [],
      selectData: [],
      tableKeyMap: {
        '订单编号': 'orderId',
        '订单日期': 'orderDate',
        '订购人': 'buyerName', // 可选
        '订购人证件号': 'ConsigneeCode', // 可选
        '商品金额': 'amount',
        '支付交易号': 'payOrderNo',
        '联系人': 'contactName',
        '收件人证件号': 'contactCode',
        '联系电话': 'contactMobile',
        '收货地址省市区': 'contactAddr',
        '详细地址': 'detailAddr',
        '使用预付卡支付': 'HNACARD',
        '运费': 'distributionfee',
        '优惠金额': 'discount',
        '实付金额': 'realPayment',
        '申报订单编号': 'source_platform_no',
        // '支付方式': 'pay_type',
        '支付时间': 'pay_time',
        '贸易类型': 'tradeType',
        '订单商品编号': 'goods_spu',
        '订单商品规格名称': 'sku_id',
        '订单商品数量': 'goods_num',
        '订单商品价格': 'goods_price'
      },
      rules: {
        goods_spu: [
          { required: true, message: '商品编号不能为空' }
        ],
        sku_id: [
          { required: true, message: '商品规格名称不能为空' }
        ],
        goods_num: [
          { required: true, message: '订单商品数量不能为空' }
        ],
        realPayment: [
          { required: true, message: '实付金额不能为空' }
        ],
        contactName: [
          { required: true, message: '联系人不能为空' }
        ],
        orderId: [
          { required: true, message: '订单编号不能为空' }
        ],
        orderDate: [
          { required: true, message: '订单日期不能为空' }
        ],
        amount: [
          { required: true, message: '商品金额不能为空' }
        ],
        contactAddr: [
          { required: true, message: '收货地址省市区不能为空' }
        ],
        detailAddr: [
          { required: true, message: '详细地址不能为空' }
        ],
        distributionfee: [
          { required: true, message: '运费不能为空' }
        ],
        discount: [
          { required: true, message: '优惠金额不能为空' }
        ],
        goods_price: [
          { required: true, message: '订单商品价格不能为空' }
        ],
        HNACARD: [
          { required: true, message: '请选择是否使用预付卡支付' }
        ]
      },
      tableHeader: [],
      tableData: [],
      columns: [],
      currentConfigAreaInfo: {},
      currentConfigAreaInfoLoading: true
    }
  },
  computed: {
    table_total_num() {
      return this.tableData.reduce((total, item) => {
        if (item.hasOwnProperty('number') && item.number !== '') {
          return total + parseInt(item.number)
        } else {
          return total
        }
      }, 0)
    }
  },
  watch: {
    'importOpen': {
      deep: true,
      immediate: true,
      handler: function(newValue, oldValue) {
        if (newValue === true) {
          // this.loadData()
        }
      }
    }
  },
  created() {

  },
  mounted() {
  },
  methods: {
    convertSerialNumberToDate(serialNumber) {
      const excelEpoch = new Date(Date.UTC(1899, 11, 30))
      const millisecondsPerDay = 24 * 60 * 60 * 1000

      const date = new Date(excelEpoch.getTime() + serialNumber * millisecondsPerDay)

      const year = date.getUTCFullYear()
      const month = String(date.getUTCMonth() + 1).padStart(2, '0')
      const day = String(date.getUTCDate()).padStart(2, '0')
      const hours = String(date.getUTCHours()).padStart(2, '0')
      const minutes = String(date.getUTCMinutes()).padStart(2, '0')
      const seconds = String(date.getUTCSeconds()).padStart(2, '0')

      const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`

      return formattedDate
    },
    getHNACARDLabel(row) {
      if (row.HNACARD == undefined) return ''
      return row.HNACARD == 1 ? '使用' : '不使用'
    },
    delRow(row) {
      this.tableData = this.tableData.filter(item => item._XID !== row._XID)
      this.$refs.plxTable.loadData(this.tableData)
    },
    copyRow(row) {
      alert('')
      // const obj = {
      //   'tray_id': row.tray_id,
      //   'number': row.number,
      //   'box_number': row.box_number,
      //   'goods_status': row.goods_status,
      //   'config_id': row.config_id,
      //   'LOT1': row.LOT1,
      //   'LOT2': row.LOT2,
      //   'LOT3': row.LOT3
      // }
      // this.tableData.push(obj)
      // this.$refs.plxTable.loadData(this.tableData)
    },
    changeTableRowNumber(row, event) {
      const item = this.tableData.find(obj => obj._XID === row._XID)
      if (isNaN(row.number) || row.number <= 0) {
        item.number = ''
      } else {
        item.number = parseInt(item.number)
      }
    },
    toggleUploadRadio(val) {

    },
    clearAllSuccess() {
      this.tableData = this.tableData.filter(item => item.isUpload !== 1)
      this.$refs.plxTable.loadData(this.tableData)
    },
    selectable({ row }) {
      return row.disabled !== 'disabled'
    },
    // 添加插入行
    insertEvent(row) {
      if (row === -1) {
        this.tableData.push({})
      } else {
        this.tableData.unshift({})
      }
      this.$refs.plxTable.loadData(this.tableData)
      // this.$refs.plxTable.reloadData(this.tableData)
    },
    // 删除选中行
    deleteChecked() {
      this.$refs.plxTable.removeCheckboxRow()
      const xids = this.multipleSelection.map(item => item._XID)
      this.tableData = this.tableData.filter(item => !xids.includes(item._XID))
      this.$refs.plxTable.loadData(this.tableData)
      // this.$refs.plxTable.reloadData(this.tableData)
      this.multipleSelection = []
    },
    close() {
      this.tableData = []
      this.multipleSelection = []
      this.btnMiddleValue = false
      this.$emit('update:importOpen', false)
      this.dialogLoading = false
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    async processBatch(startIndex, batchSize) {
      // 计算结束索引
      const endIndex = Math.min(startIndex + batchSize, this.multipleSelection.length)

      const requestData = this.multipleSelection.slice(startIndex, endIndex)
      const requestDataXIDs = requestData.map(item => item._XID)

      requestData.forEach(item => {
        item.isstatus = item.isstatus === '启用' ? 1 : 0
        item.parent_id = this.confidId
      })

      const { data: errArr } = await locationBatchCreate({ list: requestData })
      const errArrKeys = Object.keys(errArr)

      if (errArrKeys) {
        this.tableData.forEach(item => {
          if (requestDataXIDs.includes(item._XID)) {
            if (errArrKeys.includes(item._XID)) {
              item.isUpload = 0
              item.errMsg = errArr[item._XID].errMsg
            } else {
              item.isUpload = 1
              item.disabled = 'disabled'
            }
          }
        })

        this.err_xid_arr = this.err_xid_arr.concat(errArrKeys)
      }

      // 检查是否还有剩余数据需要处理
      if (endIndex < this.multipleSelection.length) {
        // 使用延迟执行来等待一段时间后继续处理下一批数据'
        await new Promise(resolve => setTimeout(resolve, 100))
        await this.processBatch(endIndex, batchSize)
      } else {
        this.multipleSelection = this.multipleSelection.filter(item => this.err_xid_arr.includes(item._XID))
        this.$refs.plxTable.clearSelection()
      }
    },
    async uploadData() {
      const data = await this.$refs.plxTable.validate(this.multipleSelection)
      let faild = false

      // 表单校验
      if (data) { // 失败
        let masStr = ''
        Object.values(data).forEach(errList => {
          errList.forEach(params => {
            const { rowIndex, column, rules } = params
            rules.forEach(rule => {
              masStr += `<p>第 ${rowIndex + 1} 行 ：${rule.message}</p>`
            })
          })
        })
        // 我用的提示是element-ui的，不要说你没安装element，就说为啥报错
        return this.$notify.error({
          title: '错误',
          dangerouslyUseHTMLString: true,
          message: masStr,
          duration: 3500
        })
      }

      // 再处理一下数据
      this.multipleSelection.forEach(item => {
        item.source_platform_no = item.orderId
        item.pay_type = '3'
        item.area_id = ''
        item.payOrderNo = ''
        item.id_card_front_img = ''
        item.id_card_back_img = ''

        if (undefined == item.contactCode) {
          item.contactCode = ''
          item.pay_time = ''
        }

        const _goods_spu = item.goods_spu.toString().split(',')
        const _sku_id = item.sku_id.toString().split(',')
        const _goods_num = item.goods_num.toString().split(',')
        const _goods_price = item.goods_price.toString().split(',')

        if ((_goods_spu.length + _sku_id.length + _goods_num.length + _goods_price.length) != _goods_spu.length * 4) {
          alert('检查订单商品是否填写正确')
          faild = true
          return
        }

        item.order_goods = []
        for (var i = 0; i < _goods_spu.length; i++) {
          item.order_goods.push({
            goods_spu: _goods_spu[i],
            sku_id: _sku_id[i],
            goods_num: parseInt(_goods_num[i]),
            goods_price: _goods_price[i]
          })
        }
        // delete item.goods_spu
        // delete item.goods_num
        // delete item.sku_id
        // delete item.goods_price

        if (this.$store.state.user.tenant_id == 10043) {
          item.ebpCode = '3201960QBE'
          item.ebpName = '南京云极跨境国际贸易有限公司'
          item.paycomCode = '460116287K'
          item.paycomName = '新生支付有限公司'
        } else {
          this.$notify.error({
            message: '请先联系管理员配置电商平台名称、代码'
          })
          faild = true
          return
        }
      })

      // console.log(this.multipleSelection)

      if (faild) return

      // 组装数据-调用接口
      importOrder2({ list: this.multipleSelection }).then(response => {
        console.log(response.code)
        if (response.code === 10000) {
          this.$notify.success({
            title: '提示',
            message: `订单导入成功！`
          })
        } else {
          console.log('1unima')
          let title = '错误'
          if (response.data !== undefined) {
            console.log(this.tableData.map(item => item._XID).indexOf(response.data))
            const _indexof = this.tableData.map(item => item._XID).indexOf(response.data)
            if (_indexof !== -1) {
              title = `第${_indexof + 1}行` + title
            }
          }

          this.$notify.error({
            title: title,
            message: response.message
          })
        }
      })
      // console.log(this.$refs.plxTable.getRowById('row_15'))
    },
    // 校验
    fullValidEvent() {
      // fullValidate完整校验，和 validate 的区别就是会给每一行进行校验
      this.$refs.plxTable.fullValidate().then(data => {
        // data就是当前检验不通过的
        if (data) {
          let masStr = ''
          Object.values(data).forEach(errList => {
            console.log(errList)
            errList.forEach(params => {
              const { rowIndex, column, rules } = params
              rules.forEach(rule => {
                masStr += `<p>第 ${rowIndex} 行 ${column.title} 校验错误：${rule.message}</p>`
              })
            })
          })
          // 我用的提示是element-ui的，不要说你没安装element，就说为啥报错
          this.$notify.error({
            title: '错误',
            dangerouslyUseHTMLString: true,
            message: masStr,
            duration: 1500
          })
        } else {
          // 我用的提示是element-ui的，不要说你没安装element，就说为啥报错
          this.$message({
            message: '校验成功',
            type: 'success',
            duration: 1500
          })
        }
      })
    },
    // 整个表格校验
    validAllEvent() {
      // 1. validate方法 如果你传入一个true， 那么就代表整个表格校验！
      // 2.快速校验，如果存在校验不通过的行，则返回不再继续校验
      this.$refs.plxTable.validate(true).then(data => {
        if (data) {
          this.$message({
            message: '校验不通过',
            type: 'error',
            duration: '1000'
          })
        } else {
          this.$message({
            message: '校验成功',
            type: 'success',
            duration: '1000'
          })
        }
      })
    },
    editRowEvent(row) {
      this.$refs.plxTable.setActiveRow(row)
    },
    consignee_label(row) {
      let label = ''
      this.clientList.forEach(item => {
        if (item.serial_number == row.consignee_serial_number) {
          label = item.account_name
        }
      })
      return label
    },
    status_label(row) {
      return row.goods_status
    },
    config_name_label(row) {
      let label = ''
      this.config_options.forEach(item => {
        if (item.config_id === row.config_id) {
          label = item.name
        }
      })
      // const result = this.config_options.find(item => item.config_id === row.config_id)
      // if (result) {
      //   if (undefined === result.stock) {
      //     label = result.name
      //   } else {
      //     label = `<span style="color:red;font-weight: 1000;">${result.name}</span><span style="color: red;font-weight: 700;">【货物数${result.stock}】</span>`
      //   }
      // }

      if (label == '' && row.configData2) {
        row.configData2.forEach(itm => {
          if (itm.config_id == row.config_id) {
            label = `<span style="color:red;font-weight: 1000;">${itm.name}</span><span style="color: blue;font-weight: 700;">【该库位属其他库区】</span>`
          }
        })
      }
      return label
    },
    project_client_label(row) {
      let label = ''
      this.selectData.forEach(item => {
        if (Array.isArray(row.project_client) && item.value == row.project_client[0]) {
          item.children.forEach(itm => {
            if (itm.value == row.project_client[1]) {
              label = item.label + '/' + itm.label
              return
            }
          })
        }
      })
      return label
    },
    project() {
      const that = this
      getProject().then(response => {
        if (response.code === 10000) {
          that.selectData = response.data
        }
      })
    },
    // 点击保存
    saveEvent(row) {
      // 判断是否发生改变
      console.log(this.$refs.plxTable.isUpdateByRow(row))
      if (this.$refs.plxTable.isUpdateByRow(row)) {
        // 局部保存，并将行数据恢复到初始状态（如果 第二个参数record 为空则不改动行数据，只恢复状态）
        // 必须执行这个，不然下次点击保存，还是保存成功哦！状态没改变哦
        this.$refs.plxTable.reloadRow(row, null, null)
        // ...保存逻辑相关（后端呀，或者前端呀）
        this.$message({
          message: '恭喜你，保存成功',
          type: 'success'
        })
      } else {
        this.$message({
          message: '保存失败，你没改变当前行的数据',
          type: 'error'
        })
      }
    },
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    handleSuccess({ results, header }) {
      this.multipleSelection = []
      this.tableData = results
      const that = this

      const newData = this.tableData.map(item => {
        const newItem = {}
        for (const key in item) {
          if (Object.prototype.hasOwnProperty.call(that.tableKeyMap, key)) {
            // newItem[that.tableKeyMap[key] || key] = item[key]
            // 去除空格，防止转化导致的兼容性，有空格
            if (typeof item[key] === 'string') {
              newItem[that.tableKeyMap[key] || key] = item[key].trim()
            } else {
              newItem[that.tableKeyMap[key] || key] = item[key]
            }
          }
        }
        return newItem
      })
      this.tableData = newData

      this.tableData.forEach(item => {
        // 预付卡
        item.HNACARD = 1

        if (item.orderDate && item.orderDate.toString().split('.').length == 2) {
          item.orderDate = this.convertSerialNumberToDate(item.orderDate)
        }

        if (item.ConsigneeCode) {
          item.ConsigneeCode = item.ConsigneeCode.replace('ID：', '')
        }

        // 库位
        if (item.config_id) {
          this.config_options.forEach(itm => {
            if (itm.name === item.config_id) {
              item.config_id = itm.config_id
            }
          })
        }
      })

      this.uploadRadio = '2'
      this.tableHeader = header

      this.$refs.plxTable.reloadData(this.tableData)
    }
  }
}
</script>
<style lang="less" scoped>
.btn-box{
  display: flex;
  justify-content: space-between;
}
/deep/ .el-dialog__body{
  padding-top: 0 !important;
}
</style>
